package com.example.myapplication.blue.connect;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;

import java.io.IOException;
import java.util.UUID;

///连接线程
public class ConnectThread extends Thread {

    ///唯一ID
    private static final UUID MY_UUID = UUID.fromString(Constant.CONNECTTION_UUID);
    ///蓝牙插座
    private final BluetoothSocket mmSocket;
    ///蓝牙设备
    private final BluetoothDevice mmDevice;
    ///蓝牙适配器
    private BluetoothAdapter mBluetoothAdapter;
    ///当前线程
    private final Handler mHandler;
    ///连接线程
    private ConnectedThread mConnectedThread;

    ///连接线程构造函数
    @SuppressLint("MissingPermission")
    public ConnectThread(BluetoothDevice device, BluetoothAdapter adapter, Handler handler) {
        // Ui将一个临时对象分配给mmSocket，因为mmSocket是最终的
        ///中间插座
        BluetoothSocket tmp = null;
        ///蓝牙设备
        mmDevice = device;
        ///蓝牙适配器
        mBluetoothAdapter = adapter;
        ///当前线程
        mHandler = handler;
        // 用BluetoothSocket连接到给定的蓝牙设备
        try {
            // MY_UUID是应用程序的UUID，客户端代码使用相同的UUID
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    ///运行线程
    @SuppressLint("MissingPermission")
    public void run() {
        // 搜索占用资源大，关掉蓝牙搜索，提高速度
        mBluetoothAdapter.cancelDiscovery();

        try {
            // socket连接，阻塞运行直到成功或抛出异常时
            mmSocket.connect();
        } catch (Exception connectException) {
            //线程发送信息
            mHandler.sendMessage(
                    ///获得消息
                    mHandler.obtainMessage(
                            //获得码
                            Constant.MSG_ERROR,
                            //连接异常问题
                            connectException)
            );
            // 失败：-关闭socket
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
        // 管理连接插座： 在单独的线程中完成管理连接的工作
        manageConnectedSocket(mmSocket);
    }

    ///管理连接插座
    private void manageConnectedSocket(BluetoothSocket mmSocket) {
        ///线程发送空消息-参数连接服务器码
        mHandler.sendEmptyMessage(Constant.MSG_CONNECTED_TO_SERVER);
        ///连接线程注入 （插座、线程）
        mConnectedThread = new ConnectedThread(mmSocket, mHandler);
        //线程开始
        mConnectedThread.start();
    }

    /**
     * 取消正在进行的连接并关闭socket
     */
    public void cancel() {
        try {
            //插座关闭
            mmSocket.close();
        } catch (IOException e) { }
    }

    /**
     * 发送数据
     */
    public void sendData(byte[] data) {
        if( mConnectedThread!=null){
            ///连接线程写数据
            mConnectedThread.write(data);
        }
    }
}